import { defineStore } from 'pinia'
import { getCurrentUserInfo } from '@/services/ApiServer/signInRequest'
import router from '../router'

export interface UserInfoDto {
  _id: string
  email: string
  nickName: string
  description: string
  avatar?: {
    url: string
    _id: string
  }
  column: string
  createdAt: string
}
interface UserState {
  userInfo: UserInfoDto | null
  token: string
}
export const useUserStore = defineStore({
  id: 'user',
  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'zhihu_user',
        storage: localStorage,
      },
    ],
  },
  state: (): UserState => {
    return {
      userInfo: null,
      token: '',
    }
  },
  getters: {
    isLogin(): boolean {
      return !!this.userInfo
    },
  },
  actions: {
    // 获取当前用户信息
    async getUserInfo() {
      const res = await getCurrentUserInfo()
      if (res && res.code === 0) {
        this.userInfo = res.data
      }
    },
    setToken(token: string) {
      this.token = token
    },
    // 退出登录
    logout(callbackUrl?: string) {
      this.userInfo = null
      this.token = ''
      router.push(callbackUrl ? `/signIn/login?callbackUrl=${callbackUrl}` : '/signIn/login')
    },
  },
})
